#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json


def response(data=None, headers=None, content_type='application/json', code=200):
    if headers is None:
        headers = {}
    if 'Content-Type' in headers:
        content_type = headers['Content-Type']
    if content_type is not None:
        headers['Content-Type'] = content_type
        if content_type.startswith('application/json') and isinstance(data, (dict, list)):
            if code in (200, 201, 400, 401, 403, 404, 409, 422):
                data = json.dumps(data)
    return {'headers': headers, 'content': data, 'code': code}


def success(data=None, headers=None):
    result = {'status': 'success', 'data': data}
    return response(result, headers=headers)


def fail(data, headers=None):
    result = {'status': 'fail', 'data': data}
    return response(result, headers=headers)
